package com.wquick.base.utils.ext

import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

fun CoroutineScope.safeLaunch(
    onError: ((Throwable) -> Unit)? = null, onLaunchBlock: () -> Unit
) {
    val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        onError?.invoke(throwable)
    }

    this.launch(exceptionHandler) {
        onLaunchBlock.invoke()
    }
}


/**
 *  ```
lifecycleScope.safeLaunch<String> {
onRequest = {
//这里请求网络或者其他耗时的操作
"1234"   //这里一定要return指定的数据，放最后一行即可
}

onSuccess = {
//成功的回调
}

onError = {
//异常的回调
}
}
 *  ```
 *
 * @param T
 * @param init
 * @receiver
 */
fun <T> CoroutineScope.safeLaunch(init: CoroutineBuilder<T>.() -> Unit) {
    val result = CoroutineBuilder<T>().apply(init)
    val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
        result.onError?.invoke(throwable)
    }

    this.launch(exceptionHandler) {
        val res: T? = result.onRequest?.invoke()
        res?.let {
            result.onSuccess?.invoke(it)
        }
    }
}

class CoroutineBuilder<T> {
    var onRequest: (suspend () -> T)? = null
    var onSuccess: ((T) -> Unit)? = null
    var onError: ((Throwable) -> Unit)? = null
}


